package com.alipay.service.impl;


import com.alipay.exception.BalanceException;
import com.alipay.model.dto.Request;
import com.alipay.model.dto.Response;
import com.alipay.model.dto.TransDto;
import com.alipay.model.enums.ResponseCodeEnum;
import com.alipay.service.AccountService;
import com.alipay.service.TransferAccountsService;
import com.alipay.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author Jun
 */
@Slf4j
@Service
public class TransferAccountsServiceImpl implements TransferAccountsService {


    @Autowired
    private AccountService accountService;

    @Override
    public Response transferAccounts(Request request) {
        log.info("transferAccounts start, request = {}", request);

        // 验证签名
        Boolean flag = accountService.signCheck(request.getSignStr(), request.getTransferInfo());
        if (!flag) {
            return Response.newFailure(request.getRequestId(), ResponseCodeEnum.BAD_REQUESTS);
        }

        // 参数有效性校验
        TransDto transDto = JsonUtil.fromJson(request.getTransferInfo(), TransDto.class);
        if (StringUtils.isEmpty(transDto.getTransId()) ||
                transDto.getAmount() == null ||
                StringUtils.isEmpty(transDto.getFromAccount()) ||
                StringUtils.isEmpty(transDto.getToAccount())) {
            return Response.newFailure(request.getRequestId(), ResponseCodeEnum.ARG_ERROR);
        }


        // 扣减出款账户余额
        try {
            accountService.decrease(transDto);
        } catch (BalanceException e) {
            log.error("decrease failed, the payerAccountId is {}, caused by {}", transDto.getFromAccount(), e);
            return Response.newFailure(request.getRequestId(), ResponseCodeEnum.BALANCE_ERROR);
        } catch (Exception e) {
            log.error("decrease failed, the payerAccountId is {}, caused by {}", transDto.getFromAccount(), e);
            return Response.newFailure(request.getRequestId(), ResponseCodeEnum.DECREASE_ERROR);
        }
        return Response.newSuccess(request.getRequestId(), null);
    }
}
